﻿using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Corina.DataContext.Service
{
    public class DeviceSaleService : ServiceBase
    {
        public DataTable GetAllItems(string connectionString, string deviceSn, int kindId, int userId, int index, int size, ref int count)
        {
            List<SqlParameter> paras = new List<SqlParameter>();
            string qstring = "SELECT * FROM ( ";
            string cstring = "SELECT COUNT(*) FROM ( ";
            StringBuilder builder = new StringBuilder();

            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY tds.Id) AS ROW_NUMBER, tds.*,td.ManufactureDate, tdk.Name AS Kind, tu.Name AS UserName, tddtt.Title AS TransferKind ");
            builder.Append("  FROM t_device_sale AS tds ");
            builder.Append("LEFT JOIN t_device AS td ON td.DeviceSn = tds.DeviceSn  ");
            builder.Append("LEFT JOIN t_device_kind AS tdk ON tdk.Id = td.DeviceKindId ");
            builder.Append("LEFT JOIN CORINA_ACCO.dbo.t_user AS tu ON tu.Id = tds.UserId ");
            builder.Append("LEFT JOIN t_device_data_transfer_type AS tddtt ON tddtt.Id = td.DataTransferTypeId ");
            builder.Append("WHERE 1=1 ");

            #region Conditions
            builder.Append("AND tds.DeviceSn LIKE @DeviceSn ");
            paras.Add(new SqlParameter("@DeviceSn", string.Format("%{0}%", deviceSn)));

            if (kindId > 0)
            {
                builder.Append("AND tdk.Id = @KindId ");
                paras.Add(new SqlParameter("@KindId", kindId));
            }

            if (userId > 0)
            {
                builder.Append("AND tu.Id = @UserId ");
                paras.Add(new SqlParameter("@UserId", userId));
            }

            #endregion

            builder.Append(") AS query ");

            count = DbOperator.GetCount(connectionString, string.Format("{0}{1}", cstring, builder), paras.ToArray());

            builder.Append("WHERE query.[ROW_NUMBER] BETWEEN @Index + 1 AND @Index + @Size ");
            paras.Add(new SqlParameter("@Index", (index - 1) * size));
            paras.Add(new SqlParameter("@Size", size));
            builder.Append("ORDER BY query.[ROW_NUMBER]");

            DataTable table = DbOperator.GetDataTable(connectionString, string.Format("{0}{1}", qstring, builder), paras.ToArray());
            return table;
        }

        public bool Insert(string connectionString,DeviceSaleInfo entity)
        {
            return DbOperator.UpdateEntity(connectionString, entity, EntityOperation.Insert);
        }

        public bool Insert(string connectionString,List<DeviceSaleInfo> entities)
        {
            return DbOperator.InsertEntities<DeviceSaleInfo>(connectionString, entities);
        }
    }
}
